﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using zijian666.Core;
using zijian666.Core.Abstractions;

namespace zijian666.Data.SqlBuilders;
class PgSqlBuilder : TSqlBuilder
{
    public static readonly PgSqlBuilder Instance = new PgSqlBuilder();
    public override string PagingSql(string sql, long begin, int count)
    {
        return $"{sql.TrimSemicolon()} LIMIT {count} OFFSET {begin}";
    }

    private DbProviderFactory _dbProvider = default!;

    public override DbParameter CreateParameter(object? value, string? typeName)
    {
        var p = base.CreateParameter(value, typeName);
        if (typeName?.Contains("jsonb", StringComparison.OrdinalIgnoreCase) is true)
        {
            ((dynamic)p).DataTypeName = "jsonb";
        }
        return p;
    }

    public override DbProviderFactory DbProvider
    {
        get
        {
            if (_dbProvider is null)
            {
                if (DbProviderFactories.TryGetFactory("Npgsql", out _dbProvider!))
                {
                    return _dbProvider;
                }
                var name = DbProviderFactories.GetProviderInvariantNames().FirstOrDefault(x => x.Contains("pgsql", StringComparison.OrdinalIgnoreCase));
                if (name is null)
                {
                    throw new NotSupportedException("未找到 pgsql 提供程序");
                }
                _dbProvider = DbProviderFactories.GetFactory(name);
            }
            return _dbProvider;
        }
    }


    public override string GetParameterHolder(string parameterName)
    {
        return $"@{parameterName}";
    }
}
